package hn.cch.grammar.net.tcp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created by CCH on 2018/5/7.
 */
public class Server {
    //多连接服务器
    public static void main(String[] args) {
        //端口
        int port = 8080;
        try {
            ServerSocket server = new ServerSocket(port);
            System.out.println("服务端开启");
            System.out.println(server);
            try {
                while (true) {
                    Socket client = server.accept();
                    System.out.println("客户端连接");
                    System.out.println(client);
                    //客户端连接服务器
                    new Connect(client).start();

                    System.out.println("输入为空关闭服务端");
                    //控制台输入
                    Scanner scanner = new Scanner(System.in);
                    String string = scanner.nextLine();
                    //为空退出
                    if (string.equals("")) {
                        break;
                    }

                }
            } finally {
                System.out.println("服务端关闭");
                server.close();
            }

        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

}

class Connect extends Thread {
    private Socket client;
    private BufferedReader reader;
    private PrintWriter writer;

    public Connect(Socket socket) {
        client = socket;
    }

    @Override
    public void run() {
        try {
            reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);

            while (true) {
                String str = reader.readLine();
                //为空退出
                if (str.equals("")) {
                    break;
                }
                System.out.println(str);
                writer.println("----------");
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                System.out.println("客户端断开");
                client.close();
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }
}
